package com.example.hospitaltraining.utils;

import cn.hutool.crypto.symmetric.SymmetricCrypto;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Hex;

import java.security.Security;


public class SM4DecryptionExample {

    static {
        Security.addProvider(new BouncyCastleProvider());
    }
    private static final String ENCODING = "UTF-8";
    public static final String ALGORITHM_NAME = "SM4";
    // 加密算法/分组加密模式/分组填充方式
    // PKCS5Padding-以8个字节为一组进行分组加密
    // 定义分组加密模式使用：PKCS5Padding
    public static final String ALGORITHM_NAME_ECB_PADDING = "SM4/ECB/PKCS5Padding";
    // 128-32位16进制；256-64位16进制
    public static final int DEFAULT_KEY_SIZE = 128;


    /**
     * 加密
     *
     * @param key 密钥
     * @param data 加密前的明文
     * @return  String 返回密文
     * @author  wx
     * @date  2023-12-08
     */

    public static String encrypt(String key, String data) {
        byte[] sm4KeyBytes = Hex.decode(key);
        SymmetricCrypto sm4 = new SymmetricCrypto("SM4/ECB/PKCS5Padding", sm4KeyBytes);
        return sm4.encryptHex(data).toUpperCase();
    }


    /**
     *
     * 解密
     * @param key 密钥
     * @param data 加密后的密文
     * @return  String 返回明文
     * @author  wx
     * @date  2023-12-08
     */

    public static String decrypt(String key,String data) {
        try{
            byte[] sm4KeyBytes = Hex.decode(key);
            SymmetricCrypto sm4 = new SymmetricCrypto("SM4/ECB/PKCS5Padding", sm4KeyBytes);
            return sm4.decryptStr(data);
        }catch (Exception e){
            return data;
        }
    }
}
